import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/foundation.dart';

export 'package:dio/dio.dart';

// 必须是顶层函数
_parseAndDecode(String response) {
  return jsonDecode(response);
}

parseJson(String text) {
  return compute(_parseAndDecode, text);
}

abstract class BaseHttp extends DioForNative {
  BaseHttp() {
    /// 初始化 加入app通用处理
    if (transformer is BackgroundTransformer) {
      (transformer as BackgroundTransformer).jsonDecodeCallback = parseJson;
    }
    init();
  }

  void init();
}

/// 添加常用Header
class HeaderInterceptor extends InterceptorsWrapper {
  @override
  onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    options.connectTimeout = Duration(seconds: 5);
    options.receiveTimeout = Duration(seconds: 45);
    super.onRequest(options, handler);
  }
}

/// 子类需要重写
abstract class BaseResponseData {
  int code = 0;
  String? message;
  dynamic data;

  BaseResponseData({this.code = 0, this.message, this.data});

  @override
  String toString() {
    return 'BaseRespData{code: $code, message: $message, data: $data}';
  }
}

/// 接口的code没有返回为true的异常
class ApiException implements Exception {
  String? message;
  BaseResponseData? data;

  ApiException({this.message, this.data});

  ApiException.fromRespData(BaseResponseData respData) {
    data = respData;
    message = respData.message;
  }
  //  @override
  //  String toString() {
  //    return 'NotExpectedException{respData: $message}';
  //  }
}

/// 用于未登录等权限不够,需要跳转授权页面
class UnAuthorizedException implements Exception {
  const UnAuthorizedException();

  @override
  String toString() => 'UnAuthorizedException';
}
